/**
 * Project Name:javaBaseReview
 * Package Name:com.xuwei.base.thread
 * author:David
 * Date:2015年8月19日下午8:45:46
 * Copyright (c) 2015, xw123box@126.com All Rights Reserved.
 *
 */
package com.xuwei.base.thread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * 传统线程同步通信技术
 * @author David
 * @since 2015年8月19日 下午8:45:46
 * @version 
 * @since JDK 1.6
 */
public class BlockingQueueCommunication {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		final Buisiness buisiness=new Buisiness();
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				for(int i=1;i<=50;i++){
					buisiness.sub(i);
				}
				
			}
		}).start();
		
		for(int i=1;i<=50;i++){
			buisiness.main(i);
		}
		
	}

	
	static class Buisiness{
		BlockingQueue<Integer> queue1=new ArrayBlockingQueue<Integer>(1);
		BlockingQueue<Integer> queue2=new ArrayBlockingQueue<Integer>(1);
		
		//匿名构造方法--在所有的构造方法之前执行
		{
			try {
				queue2.put(1);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		public  void sub(int i){
			try{
				queue1.put(1);
			}catch(InterruptedException e){
				e.printStackTrace();
			}
			
			for(int j=1;j<=10;j++){
				System.out.println("sub thread sequence of "+j+",loop of "+i);
			}
			try{
				queue2.take();
			}catch(InterruptedException e){
				e.printStackTrace();
			}
		}
		
		public void main(int j){
			try {
				queue2.put(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			for(int i=1;i<=100;i++){
				System.out.println("main thread sequence of "+i+",loop of"+j);
			}	
			try {
				queue1.take();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
		}
		
	}
	
	
}



